<template>
  <FilterNavbar>
    <template #center>
      <view class="navbar-title"> {{ pageTitle }} </view>
    </template>
  </FilterNavbar>
  <ve-form ref="ve_form" :model="form" :rules="rules" style="padding: 24rpx">
    <ve-card title="基本信息" type="none" fold v-model:initFold="foldStatus.fold1">
      <ve-form-item label="企业客户名称" prop="clientName" required :borderBottom="false">
        <ve-input v-model="form.clientName" placeholder="请输入" />
      </ve-form-item>
      <block v-if="record">
        <ve-cell label="电子合同认证状态">
          <text :class="'contract-status_'+record.ecAuthenticationStatus">{{ record.ecAuthenticationStatusName }}</text>
        </ve-cell>
        <view v-if="record.ecAuthenticationStatus == 0" class="status_reason c1 fw400 fs30">
          <view>原因：</view>
          <view v-if="record.authenticationFailedReason">{{ record.authenticationFailedReason || '-' }}</view>
        </view>
        <ve-cell label="签章方式">{{ record.contractSignWayName || '-' }}</ve-cell>
      </block>
    </ve-card>
    <ve-card title="企业联系人" type="none" fold v-model:initFold="foldStatus.fold2">
      <ve-form-item label="姓名">
        <ve-input v-model="form.linkman" placeholder="请输入" :maxlength="20" />
      </ve-form-item>

      <ve-form-item label="手机号" :borderBottom="false">
        <ve-input v-model="form.mobile" placeholder="请输入" :maxlength="11" />
      </ve-form-item>
    </ve-card>

    <ve-card title="发票信息" type="none" fold v-model:initFold="foldStatus.fold3">
      <ve-form-item label="抬头">
        <ve-input v-model="form.billTitle" placeholder="请输入" />
      </ve-form-item>
      <ve-form-item label="发票类型">
        <ve-picker-inline v-model="form.billType" placeholder="请选择" :range="dict.InvoiceTypeEnum"> </ve-picker-inline>
      </ve-form-item>
      <ve-form-item label="纳税人识别号">
        <ve-input v-model="form.taxpayerId" placeholder="请输入" />
      </ve-form-item>
      <ve-form-item label="公司地址">
        <ve-input v-model="form.address" placeholder="请输入" />
      </ve-form-item>
      <ve-form-item label="联系电话" :borderBottom="false">
        <ve-input v-model="form.billReceiverPhone" placeholder="请输入" />
      </ve-form-item>
    </ve-card>
    <ve-card title="合同信息" type="none" fold v-model:initFold="foldStatus.fold4">
      <contract-info
        :contractList="form.contractList"
        @handleAdd="handleAdd"
        @handleDelete="handleDelete"
        @handleChange="handleChange"
        :underline="false"
      />
    </ve-card>
    <ve-bottom-box size="mini">
      <ve-button type="primary" size="long" :loading="saveLoading" @click="handleSave">确认</ve-button>
    </ve-bottom-box>
  </ve-form>
</template>

<script setup>
  import { ref, reactive, provide, nextTick } from 'vue'
  import { onShow, onLoad } from '@dcloudio/uni-app'
  import { clientInfoDetail, createClientInfo, editClientInfo } from '@/api/market/member'
  import { usePageDict } from '@/hooks/useDict'
  import FilterNavbar from '@/components/FilterNavbar'
  import useFormFold from '@/hooks/useFormFold'

  import ContractInfo from './contractInfo.vue'

  const dict = usePageDict('clientInfoDict')
  const pageTitle = ref('新增企业客户')
  const form = ref({
    contractList: [],
  })
  provide('form', form)

  const validateTimeListFlag = ref(true)
  const record = ref({})
  const { foldStatus, foldValidate } = useFormFold([
    {
      key: 'fold1',
      props: ['clientName'],
    },
    {
      key: 'fold2',
      props: [],
    },
    {
      key: 'fold3',
      props: [],
    },
    {
      key: 'fold4',
      props: [],
    },
  ])
  const saveLoading = ref(false)
  const rules = ref({
    clientName: {
      required: true,
      message: '请输入企业客户名称',
    },
  })

  const resetForm = () => {
    form.value = { contractList: [] }
  }
  const ve_form = ref(null)
  const handleSave = () => {
    // 表单验证
    saveLoading.value = true
    ve_form.value.validate((valid, errors) => {
      if (valid) {
        validateTimeListFlag.value = true
        console.log(form.value.contractList)
        if (form.value.contractList.length) {
          form.value.contractList.forEach((item) => {
            if ((item.startTime && !item.endTime) || (!item.startTime && item.endTime)) {
              validateTimeListFlag.value = false
              return false
            }
          })
        }
        if (validateTimeListFlag.value) {
          if(pageTitle.value == '编辑企业客户' && form.value.clientName != record.value.clientName && (record.value.ecAuthenticationStatus == 0 || record.value.ecAuthenticationStatus == 1 || record.value.ecAuthenticationStatus == 2)){
            // 电子合同认证状态为：认证成功、认证失败、认证中时，需提示商户
            uni.showModal({
            	title: '提示',
            	content: '企业已发起电子合同认证，如修改企业客户名称，下次签署合同时，需重新认证，是否修改？',
            	success: function (res) {
            		if (res.confirm) {
            			clientInfoFn()
            		} else if (res.cancel) {
            			console.log('用户点击取消');
            		}
            	}
            });
          }else{
            clientInfoFn()
          }
        } else {
          uni.showToast({
            title: '请完善合同有效期',
            icon: 'none',
          })
        }
      } else {
        saveLoading.value = false
        foldValidate(errors)
        console.log('验证失败', errors)
      }
    })
  }

  const clientInfoFn = () =>{
    const params = {
      ...form.value,
    }
    let fetch
    if (params.id) {
      fetch = editClientInfo
    } else {
      fetch = createClientInfo
    }
    fetch(params)
      .then((res) => {
        saveLoading.value = false
        if (res.code == 200) {
          uni.showToast({
            title: '操作成功',
            icon: 'none',
          })
          uni.$emit('refreshData')
          resetForm()
          uni.navigateBack({
            delta: 1,
          })
        } else {
          saveLoading.value = false
          uni.showToast({
            title: res.message,
            icon: 'none',
          })
        }
      })
      .catch(() => {
        saveLoading.value = false
      })
  }

  const getDetail = async (id) => {
    console.log(id.id)
    const res = await clientInfoDetail({ id: id.id })
    if (res.code === 200) {
      const data = res.result
      form.value = data
      record.value = data
    }
  }

  const handleAdd = () => {
    form.value.contractList.push({})
  }

  const handleDelete = (index) => {
    form.value.contractList.splice(index, 1)
  }

  const handleChange = (op) => {
    form.value.contractList.forEach((item) => {
      if (item.signUserId == op.id) {
        item.signUserName = op.realname
      }
    })
  }

  onShow(() => {})

  onLoad((id) => {
    if (id.id) {
      getDetail(id)
      pageTitle.value = '编辑企业客户'
    }
  })
</script>

<style lang="scss" scoped>
  page {
    background: #f7f8fa;
  }
  .flex_img {
    display: flex;
    justify-content: space-around;
  }
  .ui_driving_up {
    position: relative;
    width: 284rpx;
    height: 184rpx;
    background-repeat: no-repeat;
    background-size: 100% 100%;
    overflow: hidden;
    border-radius: 16rpx;
  }
  .ui_driving_up image {
    background-repeat: no-repeat;
    background-size: 100% 100%;
    width: 100%;
    height: 100%;
  }
  .ui_driving_down {
    position: relative;
    width: 284rpx;
    height: 184rpx;
    background-repeat: no-repeat;
    background-size: 100% 100%;
    overflow: hidden;
    border-radius: 16rpx;
  }
  .ui_driving_down image {
    background-repeat: no-repeat;
    background-size: 100% 100%;
    width: 100%;
    height: 100%;
  }

  .contract-status_-1{
    color: #F53F3F;
  }
  .contract-status_0{
    color: #F53F3F;
  }
  .contract-status_1{
    color: #00B42A;
  }
  .contract-status_2{
    color: #FF7D00;
  }
  .status_reason{
    background-color: #F7F8FA;
    padding: 24rpx;
    display: flex;
    justify-content: flex-start;
    align-items: flex-start;
    view:nth-child(1){
      min-width: 80rpx;
    }
    view:nth-child(2){
      flex: 1;
    }
  }
</style>
